import md5 from 'js-md5'
const Base64 = require('js-base64').Base64
function ksort(obj) {
    //obj参数,加上时间戳
    let sortObj = {},
        keys = Object.keys(obj);
    keys.sort((a, b) => {
        const firstLetterA = a[0].toLowerCase();
        const firstLetterB = b[0].toLowerCase();
        const secondLetterA = a[1].toLowerCase();
        const secondLetterB = b[1].toLowerCase();

        if (firstLetterA < firstLetterB) {
            return 1;
        } else if (firstLetterA > firstLetterB) {
            return -1;
        } else if (secondLetterA < secondLetterB) {
            return 1;
        } else if (secondLetterA > secondLetterB) {
            return -1;
        } else {
            //给Page和Page_size排序
            const forthLetterA = a[5];
            const forthLetterB = b[5] || '';
            if (forthLetterA < forthLetterB) {
                return 1;
            } else if (forthLetterA > forthLetterB) {
                return -1;
            }
            // return 0;
        }
    });
    keys.forEach((key) => {
        if (Array.isArray(obj[key])) {
            sortObj[key] = JSON.stringify(obj[key])
        } else {
            sortObj[key] = obj[key];
        }
    })
    // console.log(sortObj, 'kobj')
    return sortObj;
};

export default function signString(obj) {
    //将所有参数倒序排列
    let kobj = ksort(obj)

    //循环kobj对象将键值对拼接成字符串
    let str = 'bf2e8ec5589ac6a8b1a1c8f823592707';
    for (let key in kobj) {
        str += key + kobj[key];
    }
    // console.log(str, '拼接字符串')



    //将str字符串做base64转换
    let baseStr = '9dae4a75d1b695b7c47ff0b36d3656d7' + Base64.encode(str)
    // console.log(baseStr, 'base64')


    let mdStr = md5(baseStr).toUpperCase()
    // console.log(mdStr, 'md5')


    let str1 = '', str2 = '';
    for (let index = 0; index < mdStr.length; index++) {
        const item = mdStr[index];
        //str1等于偶数位的所有元素拼接
        if (index % 2 === 0) {
            str1 += item
        } else {
            str2 += item
        }
    }
    // console.log(str1 + str2, '置换')
    return str1 + str2;
}